package com.tpp.controller;

import com.tpp.entity.*;
import com.tpp.service.FilmService;
import com.tpp.service.UserService;
import com.tpp.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Controller
public class CUser {
    // 等同于UserService userService = new UserService();
    // @Autowired使用，@Autowired用来new，
    @Autowired
    private UserService userService;//系统帮你new好了,可以直接用，不需要自己在写new语句

    //显示网页的请求，请求会自动根据你的名字映射并渲染网页返回给客户端
    @RequestMapping("show_login")
    public String showLogin(HttpServletRequest request,Model model){
        String time_id = request.getParameter("time_id");
        System.out.println("show_login：time_id》"+time_id);
        model.addAttribute("time_id",time_id);
        return "/static/login";//通过login映射到template下面的同名网页。html后缀不需要考虑
    }
    @RequestMapping("show_order")
    public String showOrder(HttpServletRequest request,Model model){
        int user_id = Integer.valueOf(request.getParameter("user_id"));
        int time_id = Integer.valueOf(request.getParameter("time_id"));
        System.out.println("show_order->user_id:"+user_id+"time_id:"+time_id);
        String cinema_name=userService.findCinemaNameBytimesId(time_id);
        FilmTime time_info=userService.findTimeInfoByTimesId(time_id);
        Film film_info=userService.findFilmIfoByTimesId(time_id);
        String phone_number=userService.findPhonenumberByUesrId(user_id);
        model.addAttribute("user_id",user_id);
        model.addAttribute("time_id",time_id);
        model.addAttribute("cinema_name",cinema_name);
        model.addAttribute("time_info",time_info);
        model.addAttribute("film_info",film_info);
        model.addAttribute("phone_number",phone_number);
        return "/static/order";//通过login映射到template下面的同名网页。html后缀不需要考虑
    }
    @RequestMapping("show_main")
    public String showMain(HttpServletRequest request, Model model){
        List<FilmItemShow> onlineFilms = userService.findOnlineFilms();
        for(int i=0;i<onlineFilms.size();i++){
            System.out.println(onlineFilms.get(i).toString());
        }
        List<CinemaInfo> CinemaRank = userService.findCinemaRank();
        for(int i=0;i<CinemaRank.size();i++){
            System.out.println(CinemaRank.get(i).toString());
        }
        List<FilmItemShow> AllOnlineFilm = userService.findAllOnlieFilms();
        for(int i=0;i<AllOnlineFilm.size();i++){
            System.out.println(AllOnlineFilm.get(i).toString());
        }
        List<CinemaInfo> AllCinema = userService.findAllCinema();
        for(int i=0;i<AllCinema.size();i++){
            System.out.println(AllCinema.get(i).toString());
        }
        model.addAttribute("onlineFilms", onlineFilms);
        model.addAttribute("CinemaRank", CinemaRank);
        model.addAttribute("AllOnlineFilm", AllOnlineFilm);
        model.addAttribute("AllCinema", AllCinema);
        return "/static/main";
    }

    @RequestMapping("show_Add")
    public String showAdd(HttpServletRequest request,Model model)
    {
        String time_id = request.getParameter("time_id");
        model.addAttribute("time_id",time_id);
        return "/static/user_add";
    }
    @RequestMapping("check_login")
    public String checkLogin(HttpServletRequest request,RedirectAttributes attributes){//用来接收表单或者URl传递过来的参数
        String time_id = request.getParameter("time_id");
        System.out.println("check_login：time_id》"+time_id);
        String userCode = request.getParameter("username");
        String userPwd = request.getParameter("password");
        System.out.println(userCode + "|" + userPwd );
        User user = userService.checkLogin(userCode, userPwd);
        //如果user不为null，就把它存到session里面去.
        if (user == null)
            return "/static/login";
        else {
            attributes.addAttribute("user_id", user.getUser_id());
            attributes.addAttribute("time_id", time_id);
            //跳转有2种方式，1直接跳转，2通过重定向请求跳转
            return "redirect:show_order"; //以后设置跳转订单界面
            //return "redirect:show_main";//2种方式

        }
    }
    @RequestMapping("AddOrder")
    public String AddOrder(HttpServletRequest request)
    {
        String Order_time = request.getParameter("Order_time");

        String Order_number = request.getParameter("Order_number");
        int Uesr_id = Integer.valueOf(request.getParameter("Uesr_id"));
        float Actual_money =Float.valueOf(request.getParameter("Actual_money")) ;
        int Film_times_id = Integer.valueOf(request.getParameter("Film_times_id"));
        Timestamp Order_time2=strToDate(Order_time);
        System.out.println(Order_number+"|"+Uesr_id+"|"+Actual_money+"|"+Film_times_id+"|"+Order_time);
        int i=userService.AddOrder(new Order(Order_number,Uesr_id,Actual_money,Film_times_id,Order_time2));
        if(i<1) System.out.println("用户添加失败");
        return "/static/pay";
    }
    @RequestMapping("AddOrderSeat")
    @ResponseBody
    public Result AddOrderSeat(HttpServletRequest request)
    {
        int hang =Integer.valueOf(request.getParameter("hang")) ;
        int lie = Integer.valueOf(request.getParameter("lie"));
        String orderId = request.getParameter("orderId");
        System.out.println(hang+"|"+lie+"|"+orderId);
        int i =userService.AddOrderSeat(hang,lie,orderId);

        int time_id = Integer.valueOf(request.getParameter("time_id"));
        //String Seat=request.getParameter("seat");
        String Seat=userService.findSeatInfoByTimesId1(time_id);
        System.out.println("///////////////////////////////////"+Seat);
        String newSeat="";
        int num=0;
        int count=0;
        if(hang>3){
            num=3*12+(hang-3-1)*10+lie;
        }else {
            num=(hang-1)*12+lie;
        }
        System.out.println("///////////////////////////////////"+num);
        String[] strArr=Seat.split("");
        for(int y=0;y<strArr.length;y++){
            if(strArr[y].equals("1")||strArr[y].equals("0")){
                count++;
                if(count==num){
                    strArr[y]="1";
                }
            }

        }
        for (String x:strArr) {
            newSeat+=x;
        }
        System.out.println("///////////////////////////////////"+newSeat);
        userService.updateSeat(newSeat,time_id);

        Result result=new Result();
        if(i<1) {
            result.setMsg("查询错误");
            result.setStatus(1);
        }else {
            result.setData(i);
            result.setMsg("查询成功");
            result.setStatus(0);
        }
        return result;
    }

/*    @RequestMapping("updateSeat")
    @ResponseBody
    public Result updateSeat(HttpServletRequest request){
        String newSeat = request.getParameter("newSeat");
        int time_id = Integer.valueOf(request.getParameter("time_id"));
        System.out.println("time_id::::"+newSeat);

       int i=userService.updateSeat(newSeat,time_id);
        Result result=new Result();

        if(i<1) {
            result.setMsg("查询错误");
            result.setStatus(1);
        }else {
            result.setData(i);
            result.setMsg("查询成功");
            result.setStatus(0);
        }
        return result;
    }*/
@RequestMapping("AddUser")
public String AddUser(HttpServletRequest request,RedirectAttributes attributes){
    String time_id = request.getParameter("time_id");
    String userCode = request.getParameter("username");
    String userPwd = request.getParameter("password");
    String phone = request.getParameter("phone");
    System.out.println(userCode + "|" + userPwd+"|"+time_id );
    User i = userService.checkUsername(userCode);
    //如果user不为null，就把它存到session里面去.
    if (i!=null){
        attributes.addAttribute("time_id",time_id);
        return "redirect:show_Add";
    }
    else {
        int x = userService.AddUser(userCode, userPwd,phone);
        attributes.addAttribute("time_id",time_id);
        return "redirect:show_login";


    }
}
    public static java.sql.Timestamp strToDate(String strDate) {
        String str = strDate;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        java.util.Date d = null;
        try {
            d = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        java.sql.Timestamp date = new java.sql.Timestamp(d.getTime());
        return date;
    }







    @RequestMapping("getAllUser_wx")
    @ResponseBody
    public Result getAllUser_wx(HttpServletRequest request){

        List<User> Films=userService.getAllUser_wx();
        Result result=new Result();

        if(Films.size()==0) {
            result.setMsg("查询错误");
            result.setStatus(1);
        }else {
            result.setData(Films);
            result.setMsg("查询成功");
            result.setStatus(0);
        }
        return result;
    }
    @RequestMapping("createOrder_wx")
    @ResponseBody
    public Result createOrder_wx(HttpServletRequest request){
        int timeId = Integer.valueOf(request.getParameter("timeId"));
        String username = request.getParameter("username");
        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        System.out.println("timeId:"+timeId+"|username:"+username+"|x:"+x+"|y:"+y);

        FilmTime timeInfo=userService.findTimeInfoByTimesId(timeId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(Calendar.getInstance().getTimeInMillis());// new Date()为获取当前系统时间，也可使用当前时间戳


        float Actual_money=timeInfo.Film_price;
        int UserId=userService.findUserIdByUsername(username);
        String date2=date.replace(" ","").replace("-","").replace(":","");
        String Order_nuber=UserId+timeId+date2;
        System.out.println("Order_nuber:"+Order_nuber+"Actual_money"+Actual_money);
        int i=userService.AddOrder(new Order(Order_nuber,UserId,Actual_money,timeId,strToDate(date)));
        int i1 =userService.AddOrderSeat(x,y,Order_nuber);
        //String Seat=request.getParameter("seat");
        String Seat=userService.findSeatInfoByTimesId1(timeId);
        System.out.println("///////////////////////////////////"+Seat);
        String newSeat="";
        int num=0;
        int count=0;
        if(x>3){
            num=3*12+(x-3-1)*10+y;
        }else {
            num=(x-1)*12+y;
        }
        System.out.println("///////////////////////////////////"+num);
        String[] strArr=Seat.split("");
        for(int z=0;z<strArr.length;z++){
            if(strArr[z].equals("1")||strArr[z].equals("0")){
                count++;
                if(count==num){
                    strArr[z]="1";
                }
            }

        }
        for (String t:strArr) {
            newSeat+=t;
        }
        System.out.println("///////////////////////////////////"+newSeat);
        userService.updateSeat(newSeat,timeId);
        Result result=new Result();

       /* if(order.size()==0) {
            result.setMsg("更新失败");
            result.setStatus(1);
        }else {
            result.setData(order);
            result.setMsg("更新成功");
            result.setStatus(0);
        }*/
        return result;
    }
}
